<?php
if (!defined('FosfoaSystem')) {
    exit(1);
}
class email_templateModel extends spModel
{
    var $pk = "id"; // 每个唯一的标志，可以称为主键
    var $table = "email_template"; // 数据表的名称
    public function Detail($id)
    {
        $condition = array('id' => $id);
        $arr = $this->find($condition);
        return $arr;
    }
    /**
     * 邮件发送函数
     * @param $to  收信人邮件
     * @param $To_Name 收信人名称
     * @param $From_Email 发信人邮件
     * @param $From_Name  发信人名称
     * @param $Subject 发信主题
     * @param $body 发信内容
     */
    public function Sendmail($to, $To_Name, $From_Email, $From_Name, $Subject, $body)
    {
        //date_default_timezone_set('America/Toronto');
        
        $PHPMailer = spClass('PHPMailer',null,null, True); //邮件发送类

        if (SEND_TYPE == "smtp") {
            $PHPMailer->IsSMTP(); // telling the class to use SMTP
            $PHPMailer->SMTPDebug = SMTP_DEBUG;
            $PHPMailer->SMTPAuth = SMTP_AUTHENTICATE; // enable SMTP authentication
            $PHPMailer->Port = MAILPORT; // set the SMTP port
            $PHPMailer->Host = SMTP; // SMTP server
            $PHPMailer->Username = MAILUSER; // SMTP account username
            $PHPMailer->Password = MAILPASS; // SMTP account password
        } elseif (SEND_TYPE == "mail") {
            $PHPMailer->IsMail(); // telling the class to use PHP's Mail()
        } elseif (SEND_TYPE == "sendmail") {
            $PHPMailer->IsSendmail(); // telling the class to use Sendmail
        } elseif (SEND_TYPE == "qmail") {
            $PHPMailer->IsQmail(); // telling the class to use Qmail
        }
        //$PHPMailer->AddReplyTo(MAILUSER, STORENAME); //接收回复
        if ($From_Name != '') {
            $PHPMailer->AddReplyTo($From_Email, $From_Name);
            $PHPMailer->From = MAILUSER;
            $PHPMailer->FromName = STORENAME;
        } else {
            $PHPMailer->AddReplyTo($From_Email);
            $PHPMailer->From = MAILUSER;
            $PHPMailer->FromName = STORENAME;
        }

        if ($To_Name != '') {
            $PHPMailer->AddAddress($to, $To_Name);
        } else {
            $PHPMailer->AddAddress($to);
        }
        $PHPMailer->Subject = $Subject;
        $PHPMailer->AltBody = strip_tags($body);
        $PHPMailer->WordWrap = 80; // set word wrap
        $PHPMailer->MsgHTML($body); //邮件内容
        //$PHPMailer->AddAttachment("images/aikido.gif", "aikido.gif"); // attachment附件
        try {
            if (!$PHPMailer->Send()) {
                //              $error = "Unable to send to: " . $to . "<br />";
                //              throw new phpmailerAppException($error);
                return false;
            } else {
                return true;
            }
        }
        catch (phpmailerException $e) {
            //$errorMsg[] = $e->errorMessage();
            return false;
        }
        //      if ( count($errorMsg) > 0 ) {
        //        foreach ($errorMsg as $key => $value) {
        //          $thisError = $key + 1;
        //          echo $thisError . ': ' . $value;
        //        }
        //      }
    }

    public function mail_replace($body, $usermail, $fullname)
    {

        $email_greeting = T('EMAIL_GREET_NONE');
        $name = $fullname;


        //echo $usermail;
        $body = str_replace("#ORDER_TOP#", T('ORDER_TOP'), $body);
        $body = str_replace("#EMAIL_GREETING#", $email_greeting, $body);
        $body = str_replace("#NAME#", $name, $body);
        $body = str_replace("#THANK_YOU_FOR_REGISTERING#", T('THANK_YOU_FOR_REGISTERING'),$body);
        $body = str_replace("#YOU_MAY_NOW_LOG_IN#", T('YOU_MAY_NOW_LOG_IN'), $body);
        $body = str_replace("#USERNAME#", T('Username'), $body);
        $body = str_replace("#USERMAIL#", $usermail, $body);
        $body = str_replace("#PASSWORD#", T('Password'), $body);
        $body = str_replace("#USERPASS#", '********', $body);
        $body = str_replace("#AFTER_SUCCESSFUL_REGISTRATION#", $After_successful_registration,$body);
        $body = str_replace("#CAN-SPAM#", T('CAN-SPAM'), $body);

        $body = str_replace("#ORDER_PAY_TOP#", T('ORDER_PAY_TOP'), $body);
        $body = str_replace("#ORDERS#", T('ORDERS'), $body);
        $body = str_replace("#ORDER_OTHER#", T('ORDER_OTHER'), $body);
        $body = str_replace("#ORDER_CUSTOMERS_FULLNAME#", $fullname, $body);
        
        
        $body = str_replace("#ORDER_BODY#", T('ORDER_BODY'), $body);
        
        $body = str_replace("#PAYMENT_BODY#", T('PAYMENT_BODY'), $body);
        $body = str_replace("#EMAIL_WELCOME#", T('EMAIL_WELCOME'), $body);
        $body = str_replace("#COUPON_BLOCK#", T('EMAIL_TEXT'), $body);
        $body = str_replace("#EMAIL_GV_CLOSURE#", T('EMAIL_GV_CLOSURE'), $body);
        $body = str_replace("#EMAIL_DISCLAIMER_NEW_CUSTOMER#", T('EMAIL_DISCLAIMER_NEW_CUSTOMER'),$body);
        $body = str_replace("#Copyright#", T('Copyright'), $body);
        $body = str_replace("#FORGOTTEN#", T('FORGOTTEN'), $body);
        //echo $body;

        return $body;
    }
    /**
     * 发送订单给客户 
     */
    public function order_send($orders_sn)
    {
        //这里将放置付款成功提醒邮件
        $conditions = array("orders_sn" => $orders_sn);
        $orderview=spClass('orderModel')->find($conditions);
        //dump($orderview);
        $orders_id=$orderview[orders_id];
        $orders_productstj=array('orders_id'=>$orders_id);
        $orderview[orders_products]=spClass('orders_productsModel')->findAll($orders_productstj); 
        $email_address = $orderview['customers_email_address'];
        $fullname = $orderview['customers_name'];
        
        $order_date=date("l dS \of F Y h:i:s A",$orderview[last_modified]);
        $subject='Order Confirmation No: '.$orders_sn;
        //付款后通知模板
        $str = $this->Detail(4);
        $body = $str['content'];
        $body = $this->mail_replace($body, $email_address, $fullname);
        $body = str_replace("#ORDER_SN#", $orders_sn, $body);
        $body = str_replace("#ORDER_DATE#", $order_date, $body);
        $body = str_replace("#ORDER_ID#", $orders_id, $body);
        $orders_list = '';
        foreach ($orderview[orders_products] as $k => $v) {
            $products_size=$v[product_size]<>''?' ('.$v[product_size].') ':'';
            $orders_list = $orders_list . $v[products_quantity] . ' x ' . $v[products_name] .$products_size.' '. $orderview[currency_left].$v['discounted_price'] . ' = ' .
                $orderview[currency_left] . $v[final_priceview_price] .
                '<br />';
        }
        $body = str_replace("#ORDER_LIST#", $orders_list, $body);
        $SubTotal = $orderview[currency_left] . $orderview[order_total];
        $Discount = $orderview['currency_left']. $orderview['order_discount'];
        $Shipping = $orderview[shipping_module_code].':'.$orderview[currency_left] . $orderview[shipping_method] * $orderview[currency_value];
        $Total = $orderview[currency_left] . ($orderview[shipping_method] * $orderview[currency_value] + $orderview[order_total] - $orderview['order_discount']);
        $body = str_replace("#Sub-Total#", $SubTotal, $body);
        $body = str_replace("#Shipping#", $Shipping, $body);
        $body = str_replace("#Discount#", $Discount, $body);
        $body = str_replace("#Total#", $Total, $body);
        
        $body = str_replace("#delivery_name#", $orderview[delivery_name], $body);
        $body = str_replace("#delivery_street_address#", $orderview[delivery_street_address], $body);
        $body = str_replace("#delivery_suburb#", $orderview[delivery_suburb], $body);
        $body = str_replace("#delivery_city#", $orderview[delivery_city], $body);
        $body = str_replace("#delivery_postcode#", $orderview[delivery_postcode], $body);
        $body = str_replace("#delivery_state#", $orderview[delivery_state], $body);
        $body = str_replace("#delivery_country#", $orderview[delivery_country], $body);
        $body = str_replace("#billing_name#", $orderview[billing_name], $body);
        $body = str_replace("#billing_street_address#", $orderview[billing_street_address], $body);
        $body = str_replace("#billing_suburb#", $orderview[billing_suburb], $body);
        $body = str_replace("#billing_city#", $orderview[billing_city], $body);
        $body = str_replace("#billing_postcode#", $orderview[billing_postcode], $body);
        $body = str_replace("#billing_state#", $orderview[billing_state], $body);
        $body = str_replace("#billing_country#", $orderview[billing_country], $body);
        $body = str_replace("#payment_method#", $orderview[payment_method], $body);
        
        //echo $body;
        //exit;
        
        $this->Sendmail($orderview[customers_email_address], $orderview[customers_name], REPLYEMAIL, STORENAME, $subject,$body);
        $this->order_sendtoadmin($orders_sn);
        
        
    }
    /**
     * 西联发送订单给客户 
     */
    public function order_send_westernumion($orders_sn)
    {
        //这里将放置付款成功提醒邮件
        $conditions = array("orders_sn" => $orders_sn);
        $orderview=spClass('orderModel')->find($conditions);
        //dump($orderview);
        $orders_id=$orderview[orders_id];
        $orders_productstj=array('orders_id'=>$orders_id);
        $orderview[orders_products]=spClass('orders_productsModel')->findAll($orders_productstj); 
        $email_address = $orderview['customers_email_address'];
        $fullname = $orderview['customers_name'];
        
        $order_date=date("l dS \of F Y h:i:s A",$orderview[last_modified]);
        $subject='This order('.$orders_sn.')is still pending for payment ';
        //付款后通知模板
        $str = $this->Detail(3);
        $body = $str['content'];
        $body = $this->mail_replace($body, $email_address, $fullname);

        $body = str_replace("#ORDER_SN#", $orders_sn, $body);
        $body = str_replace("#ORDER_DATE#", $order_date, $body);
        $body = str_replace("#ORDER_ID#", $orders_id, $body);
        $orders_list = '';
        foreach ($orderview[orders_products] as $k => $v) {
            $products_size=$v[product_size]<>''?' ('.$v[product_size].') ':'';
            $orders_list = $orders_list . $v[products_quantity] . ' x ' . $v[products_name] .$products_size.' '. $orderview[currency_left].$v['discounted_price'] . ' = ' .
                $orderview[currency_left] . $v[final_priceview_price] .
                '<br />';
        }
        $body = str_replace("#ORDER_LIST#", $orders_list, $body);
        $SubTotal = $orderview[currency_left] . $orderview[order_total];
        
        $Shipping = $orderview[shipping_module_code].':'.$orderview[currency_left] . $orderview[shipping_method] * $orderview[currency_value];
        $Discount = $orderview['currency_left']. $orderview['order_discount'];
        $Total = $orderview[currency_left] . ($orderview[shipping_method] * $orderview[currency_value] + $orderview[order_total] - $orderview['order_discount']);
        $body = str_replace("#Sub-Total#", $SubTotal, $body);
        $body = str_replace("#Shipping#", $Shipping, $body);
        $body = str_replace("#Discount#", $Discount, $body);
        $body = str_replace("#Total#", $Total, $body);
        
        $body = str_replace("#delivery_name#", $orderview[delivery_name], $body);
        $body = str_replace("#delivery_street_address#", $orderview[delivery_street_address], $body);
        $body = str_replace("#delivery_suburb#", $orderview[delivery_suburb], $body);
        $body = str_replace("#delivery_city#", $orderview[delivery_city], $body);
        $body = str_replace("#delivery_postcode#", $orderview[delivery_postcode], $body);
        $body = str_replace("#delivery_state#", $orderview[delivery_state], $body);
        $body = str_replace("#delivery_country#", $orderview[delivery_country], $body);
        $body = str_replace("#billing_name#", $orderview[billing_name], $body);
        $body = str_replace("#billing_street_address#", $orderview[billing_street_address], $body);
        $body = str_replace("#billing_suburb#", $orderview[billing_suburb], $body);
        $body = str_replace("#billing_city#", $orderview[billing_city], $body);
        $body = str_replace("#billing_postcode#", $orderview[billing_postcode], $body);
        $body = str_replace("#billing_state#", $orderview[billing_state], $body);
        $body = str_replace("#billing_country#", $orderview[billing_country], $body);
        $body = str_replace("#payment_method#", $orderview[payment_method], $body);
        
        //echo $body;
        //exit;
        
        $this->Sendmail($orderview[customers_email_address], $orderview[customers_name], REPLYEMAIL, STORENAME, $subject,$body);
        $this->order_sendtoadmin_westernumion($orders_sn);
        
        
    }
    /**
     * 西联发送订单信息给管理员 
     */
    public function order_sendtoadmin_westernumion($orders_sn)
    {
        //这里将放置付款成功提醒邮件
        $conditions = array("orders_sn" => $orders_sn);
        $orderview=spClass('orderModel')->find($conditions);
        //dump($orderview);
        $orders_id=$orderview[orders_id];
        $orders_productstj=array('orders_id'=>$orders_id);
        $orderview[orders_products]=spClass('orders_productsModel')->findAll($orders_productstj); 
        $email_address = $orderview['customers_email_address'];
        $fullname = $orderview['customers_name'];
        
        $order_date=date("l dS \of F Y h:i:s A",$orderview[last_modified]);
        $subject='This order('.$orders_sn.')is still pending for payment ';
        //付款后通知模板
        $str = $this->Detail(3);
        $body = $str['content'];
        $body = $this->mail_replace($body, $email_address, $fullname);
        $body = str_replace("#ORDER_SN#", $orders_sn, $body);
        $body = str_replace("#ORDER_DATE#", $order_date, $body);
        $body = str_replace("#ORDER_ID#", $orders_id, $body);
        $orders_list = '';
        foreach ($orderview[orders_products] as $k => $v) {
            $products_size=$v[product_size]<>''?' ('.$v[product_size].') ':'';
            $orders_list = $orders_list . $v[products_quantity] . ' x ' . $v[products_name] .$products_size.' '. $orderview[currency_left].$v['discounted_price'] . ' = ' .
                $orderview[currency_left] . $v[final_priceview_price] .
                '<br />';
        }
        $body = str_replace("#ORDER_LIST#", $orders_list, $body);
        $SubTotal = $orderview[currency_left] . $orderview[order_total];
        $Discount = $orderview['currency_left']. $orderview['order_discount'];
        $Shipping = $orderview[shipping_module_code].':'.$orderview[currency_left] . $orderview[shipping_method] * $orderview[currency_value];
        $Total = $orderview[currency_left] . ($orderview[shipping_method] * $orderview[currency_value] + $orderview[order_total] - $orderview['order_discount']);
        $body = str_replace("#Sub-Total#", $SubTotal, $body);
        $body = str_replace("#Shipping#", $Shipping, $body);
        $body = str_replace("#Discount#", $Discount, $body);
        $body = str_replace("#Total#", $Total, $body);
        
        $body = str_replace("#delivery_name#", $orderview[delivery_name], $body);
        $body = str_replace("#delivery_street_address#", $orderview[delivery_street_address], $body);
        $body = str_replace("#delivery_suburb#", $orderview[delivery_suburb], $body);
        $body = str_replace("#delivery_city#", $orderview[delivery_city], $body);
        $body = str_replace("#delivery_postcode#", $orderview[delivery_postcode], $body);
        $body = str_replace("#delivery_state#", $orderview[delivery_state], $body);
        $body = str_replace("#delivery_country#", $orderview[delivery_country], $body);
        $body = str_replace("#billing_name#", $orderview[billing_name], $body);
        $body = str_replace("#billing_street_address#", $orderview[billing_street_address], $body);
        $body = str_replace("#billing_suburb#", $orderview[billing_suburb], $body);
        $body = str_replace("#billing_city#", $orderview[billing_city], $body);
        $body = str_replace("#billing_postcode#", $orderview[billing_postcode], $body);
        $body = str_replace("#billing_state#", $orderview[billing_state], $body);
        $body = str_replace("#billing_country#", $orderview[billing_country], $body);
        $body = str_replace("#payment_method#", $orderview[payment_method], $body);
        $body = $body.'<br/>-----<br/>'.T("EMAIL_DISCLAIMER_NEW_CUSTOMER").'<br/><br/>-----<br/>'.T("Copyright").T('Localinfo');
        
        $localinfo=$this->localinfo();
        $body = str_replace("#email#", $orderview[customers_email_address], $body);
        $body = str_replace("#loginemail#", $localinfo[loginemail], $body);
        $body = str_replace("#ip#", $localinfo[ip], $body);
        $body = str_replace("#loginname#", $localinfo[loginname], $body);
        $body = str_replace("#emailtime#", $localinfo[emailtime], $body);
        //echo $body;
        //exit;
        
        //$this->Sendmail($orderview[customers_email_address], $orderview[customers_name], REPLYEMAIL, STORENAME, $subject,$body);
        $this->Sendmail(REPLYEMAIL, null, REPLYEMAIL, STORENAME, '[NEW ORDER] '.$subject,$body);
        
    }    
    /**
     * 发送订单信息给管理员 
     */
    public function order_sendtoadmin($orders_sn)
    {
        //这里将放置付款成功提醒邮件
        $conditions = array("orders_sn" => $orders_sn);
        $orderview=spClass('orderModel')->find($conditions);
        //dump($orderview);
        $orders_id=$orderview[orders_id];
        $orders_productstj=array('orders_id'=>$orders_id);
        $orderview[orders_products]=spClass('orders_productsModel')->findAll($orders_productstj); 
        $email_address = $orderview['customers_email_address'];
        $fullname = $orderview['customers_name'];
        
        $order_date=date("l dS \of F Y h:i:s A",$orderview[last_modified]);
        $subject='Order Confirmation No: '.$orders_sn;
        //付款后通知模板
        //$str = $this->Detail(4);
        $body = T('ORDER_PAY_TOP').T('ORDERS');
        $body = $this->mail_replace($body, $email_address, $fullname);
        $body = str_replace("#ORDER_SN#", $orders_sn, $body);
        $body = str_replace("#ORDER_DATE#", $order_date, $body);
        $body = str_replace("#ORDER_ID#", $orders_id, $body);
        $orders_list = '';
        foreach ($orderview[orders_products] as $k => $v) {
            $products_size=$v[product_size]<>''?' ('.$v[product_size].') ':'';
            $orders_list = $orders_list . $v[products_quantity] . ' x ' . $v[products_name] .$products_size.' '. $orderview[currency_left].$v['discounted_price'] . ' = ' .
                $orderview[currency_left] . $v[final_priceview_price] .
                '<br />';
        }
        $body = str_replace("#ORDER_LIST#", $orders_list, $body);
        $SubTotal = $orderview[currency_left] . $orderview[order_total];
        $Discount = $orderview['currency_left']. $orderview['order_discount'];
        $Shipping = $orderview[shipping_module_code].':'.$orderview[currency_left] . $orderview[shipping_method] * $orderview[currency_value];
        $Total = $orderview[currency_left] . ($orderview[shipping_method] * $orderview[currency_value] + $orderview[order_total] - $orderview['order_discount']);
        $body = str_replace("#Sub-Total#", $SubTotal, $body);
        $body = str_replace("#Shipping#", $Shipping, $body);
        $body = str_replace("#Discount#", $Discount, $body);
        $body = str_replace("#Total#", $Total, $body);
        
        $body = str_replace("#delivery_name#", $orderview[delivery_name], $body);
        $body = str_replace("#delivery_street_address#", $orderview[delivery_street_address], $body);
        $body = str_replace("#delivery_suburb#", $orderview[delivery_suburb], $body);
        $body = str_replace("#delivery_city#", $orderview[delivery_city], $body);
        $body = str_replace("#delivery_postcode#", $orderview[delivery_postcode], $body);
        $body = str_replace("#delivery_state#", $orderview[delivery_state], $body);
        $body = str_replace("#delivery_country#", $orderview[delivery_country], $body);
        $body = str_replace("#billing_name#", $orderview[billing_name], $body);
        $body = str_replace("#billing_street_address#", $orderview[billing_street_address], $body);
        $body = str_replace("#billing_suburb#", $orderview[billing_suburb], $body);
        $body = str_replace("#billing_city#", $orderview[billing_city], $body);
        $body = str_replace("#billing_postcode#", $orderview[billing_postcode], $body);
        $body = str_replace("#billing_state#", $orderview[billing_state], $body);
        $body = str_replace("#billing_country#", $orderview[billing_country], $body);
        $body = str_replace("#payment_method#", $orderview[payment_method], $body);
        $body = $body.'<br/>-----<br/>'.T("EMAIL_DISCLAIMER_NEW_CUSTOMER").'<br/><br/>-----<br/>'.T("Copyright").T('Localinfo');
        
        $localinfo=$this->localinfo();
        $body = str_replace("#email#", $orderview[customers_email_address], $body);
        $body = str_replace("#loginemail#", $localinfo[loginemail], $body);
        $body = str_replace("#ip#", $localinfo[ip], $body);
        $body = str_replace("#loginname#", $localinfo[loginname], $body);
        $body = str_replace("#emailtime#", $localinfo[emailtime], $body);
        //echo $body;
        //exit;
        
        //$this->Sendmail($orderview[customers_email_address], $orderview[customers_name], REPLYEMAIL, STORENAME, $subject,$body);
        $this->Sendmail(REPLYEMAIL, null, REPLYEMAIL, STORENAME, '[NEW ORDER] '.$subject,$body);
        
    }
    
    /**
     * 发送联系我们
     */
    public function send_contact_us($email,$contactname,$enquiry)
    {
        $localinfo=$this->localinfo();
        $subject = T('contact_us_subject');
        $subject = str_replace("#ip#", $localinfo[ip], $subject);
        $body = T('contact_us_body').T('Localinfo');
        $body = str_replace("#contactname#", $contactname, $body);
        $body = str_replace("#enquiry#", $enquiry, $body);
        $body = str_replace("#email#", $email, $body);
        $body = str_replace("#loginemail#", $localinfo[loginemail], $body);
        $body = str_replace("#ip#", $localinfo[ip], $body);
        $body = str_replace("#loginname#", $localinfo[loginname], $body);
        $body = str_replace("#emailtime#", $localinfo[emailtime], $body);
        
        if ($this->Sendmail(REPLYEMAIL,REPLYEMAIL,$email, $contactname,  $subject, $body))
                {
                    return True;
                }
        return false;
    }
    public function send_create_account($email_address, $fullname,$password)
    {
        $str = $this->Detail(1);
        $body = $this->mail_replace($str['content'], $email_address, $fullname);
        $body = str_replace('********',$password,$body);
        if ($this->Sendmail($email_address, $fullname, REPLYEMAIL,STORENAME, T('EMAIL_SUBJECT'), $body))
        {
          return True;
        }
    }
    
    
    /**
    * 返回当前用户信息
    */
    public function localinfo()
    {
        if (isset($_COOKIE['abcsession_id']))
        {
            $customers = spClass('customersSession')->read();//从SEESSION表中获取当前用户信息
            $customers = unserialize($customers);//反序例化
            $userarr = $customers;//给程序中使用
        }
        $local[ip]=getIP();
        $userid=$userarr['customers_id'];
        $local[loginname]= $userid<>"" ? $userarr['customers_firstname'].' '. $userarr['customers_lastname']:"Not logged in";
        $local[loginemail]= $userid<>"" ? $userarr['customers_email_address']:"Not logged in";
        $local[emailtime]=date("l dS \of F Y h:i:s A");
        return $local;
    }
    
    /**
     * 检测EMAIL
     */
    public function isemail($val)
    {
        return preg_match('/^[A-Za-z0-9]+([._\-\+]*[A-Za-z0-9]+)*@([A-Za-z0-9-]+\.)+[A-Za-z0-9]+$/',
            $val);
    }
}